import { Dropdown, Flex } from 'antd';
import { CheckOutlined, SortAscendingOutlined, SortDescendingOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import { memo, useState } from 'react';
import { useUpdateEffect } from 'ahooks';

const SortDropdownFlex = styled(Flex)`
  cursor: pointer;
`;

const CheckOutlinedIcon = styled(CheckOutlined)`
  color: var(${'--ant-color-primary'});
`;

function Item({ selected, value }) {
  return (
    <Flex justify="space-between" align="center">
      {value}
      {selected && <CheckOutlinedIcon />}
    </Flex>
  );
}

/**
 * 排序下拉菜单组件
 *
 * @param {Object} props 属性
 * @param {Object} props.fieldMap 字段键值对 (必填)
 * @param {string} props.defaultField 默认排序字段 (必填)
 * @param {string} props.defaultSort 默认排序方式 (可选，默认降序)
 * @param {Function} props.onChange 排序变化回调函数 (可选)
 */
function SortDropdown(props) {
  // 字段键值对
  const fieldMap = props.fieldMap;

  const [selectedField, setSelectedField] = useState(props?.defaultField);
  const [selectedSort, setSelectedSort] = useState(props?.defaultSort || 'asc');

  useUpdateEffect(() => {
    if (props?.onChange) {
      props.onChange(selectedField, selectedSort);
    }
  }, [selectedField, selectedSort]);

  // 排序键值对
  const sortMap = {
    asc: '升序',
    desc: '降序'
  };

  // 获取选项列表
  function getItems() {
    const fieldItems = Object.entries(fieldMap).map(([key, value]) => {
      return {
        key,
        label: <Item selected={key === selectedField} value={value} />,
        onClick: () => {
          setSelectedField(key);
        }
      };
    });
    const sortItems = Object.entries(sortMap).map(([key, value]) => {
      return {
        key,
        label: <Item selected={key === selectedSort} value={value} />,
        onClick: () => {
          setSelectedSort(key);
        }
      };
    });
    return [...fieldItems, { type: 'divider' }, ...sortItems];
  }

  // 获取字段名称
  function getFieldName() {
    return fieldMap[selectedField];
  }

  return (
    <Dropdown menu={{ items: getItems() }} trigger={['click']}>
      <SortDropdownFlex align="center" justify="center" gap={4}>
        {selectedSort === 'asc' ? <SortAscendingOutlined /> : <SortDescendingOutlined />}
        {`按${getFieldName()}排序`}
      </SortDropdownFlex>
    </Dropdown>
  );
}

export default memo(SortDropdown);
